package com.goods.business.service.imp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goods.business.converter.inStockConverter;
import com.goods.business.mapper.InStockInfoMapper;
import com.goods.business.mapper.ProductMapper;
import com.goods.business.mapper.SupplierMapper;
import com.goods.business.mapper.inStockMapper;
import com.goods.business.service.inStockService;
import com.goods.common.model.business.InStock;
import com.goods.common.model.business.InStockInfo;
import com.goods.common.model.business.Product;
import com.goods.common.model.business.Supplier;
import com.goods.common.response.ActiveUser;
import com.goods.common.vo.business.InStockDetailVO;
import com.goods.common.vo.business.InStockItemVO;
import com.goods.common.vo.business.InStockVO;
import com.goods.common.vo.business.SupplierVO;
import com.goods.common.vo.system.PageVO;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * projectName: goods
 *
 * @author: ysc
 * time: 2022/12/4 20:23 周日
 * description:
 */
@Service
public class inStockServiceImpl implements inStockService {


    @Autowired
    private inStockMapper inStockMapper;
    @Autowired
    private inStockConverter inStockConverter;
    @Autowired
    private SupplierMapper supplierMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private InStockInfoMapper inStockInfoMapper;



//    //获取入库列表
//    @Override
//    public PageVO<InStockVO> findInStockList(Integer pageNum, Integer pageSize, InStockVO inStockVO) {
//        //1.通过工具类进行分页
//        PageHelper.startPage(pageNum,pageSize);
//        //2.创建example实例对象
//        Example example =new Example(InStock.class);
//        //3.创建对象的条件构造器
//        Example.Criteria criteria = example.createCriteria();
//        //4.入库根据创建时间进行排序
//        example.setOrderByClause("create_time desc");
//        if (inStockVO.getInNum()!=null && !"".equals(inStockVO.getInNum())){
//            criteria.andLike("inNum","%"+inStockVO.getInNum()+"%");
//        }
//        if (inStockVO.getType()!=null){
//            criteria.andEqualTo("type",inStockVO.getType());
//        }
//        if (inStockVO.getStatus()!=null){
//            criteria.andEqualTo("status",inStockVO.getStatus());
//        }
//        if(inStockVO.getStartTime()!=null){
//            criteria.andGreaterThanOrEqualTo("createTime",inStockVO.getStartTime());
//        }
//        if(inStockVO.getEndTime()!=null){
//            criteria.andLessThanOrEqualTo("createTime",inStockVO.getEndTime());
//        }
//        List<InStock> inStocks = inStockMapper.selectByExample(example);
//        List<InStockVO> inStockVOS = inStockConverter.converterToVOList(inStocks);
//        PageInfo<InStock> inStockVOPageInfo =new PageInfo<>(inStocks);
//        return new PageVO<>(inStockVOPageInfo.getTotal(), inStockVOS);
//    }


    //获取入库列表
    @Override
    public PageVO<InStockVO> findInStockList(Integer pageNum, Integer pageSize, InStockVO inStockVO) {
        PageHelper.startPage(pageNum,pageSize);
        Integer status = inStockVO.getStatus();
        @NotNull(message = "入库单类型不能为空") Integer type = inStockVO.getType();
        String inNum = inStockVO.getInNum();
        Date startTime = inStockVO.getStartTime();
        Date endTime = inStockVO.getEndTime();
        List<InStockVO> inStockVOList =inStockMapper.findInStockList(status,type,inNum,startTime,endTime);
        PageInfo<InStockVO> info = new PageInfo<>(inStockVOList);
        return new PageVO<>(info.getTotal(), inStockVOList);
    }

    //入库明细
    @Override
    public InStockDetailVO detail(Long inStockId) {
        InStockDetailVO inStockDetailVO=inStockMapper.detail(inStockId);
        PageInfo<InStockItemVO> inStockItemVOPageInfo =new PageInfo<>(inStockDetailVO.getItemVOS());
        inStockDetailVO.setTotal(inStockItemVOPageInfo.getTotal());
        return inStockDetailVO;
    }


    //添加入库信息
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addIntoStock(InStockVO inStockVO) throws Exception{
        //判断来源
        Supplier supplier = new Supplier();
        if (inStockVO.getSupplierId() == null ){
            //新增来源
            supplier.setName(inStockVO.getName());
            supplier.setAddress(inStockVO.getAddress());
            supplier.setEmail(inStockVO.getEmail());
            supplier.setPhone(inStockVO.getPhone());
            supplier.setSort(inStockVO.getSort());
            supplier.setContact(inStockVO.getContact());
            supplier.setCreateTime(new Date());
            supplier.setModifiedTime(new Date());
            //插入进去
            supplierMapper.insert(supplier);
        }
        //添加到入库记录表中
        InStock inStock = new InStock();
        inStock.setType(inStockVO.getType());
        //获取当前用户的用户名称
        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        inStock.setOperator(activeUser.getUser().getUsername());
        //遍历集合把他们number相加
        //todo:实体类 instock 中 list集合类型是obkject ， 需要改成map
        List<Map> productList = inStockVO.getProducts();
        Integer num = 0;
        for (Map product: productList){
            Integer productNumber = (Integer) product.get("productNumber");
            num=productNumber+num;
        }
        inStock.setProductNumber(num);
        if (inStockVO.getSupplierId() == null){
            inStock.setSupplierId(supplier.getId());
        }else {
            inStock.setSupplierId(inStockVO.getSupplierId());
        }
        inStock.setSupplierId(inStockVO.getSupplierId());
        inStock.setRemark(inStockVO.getRemark());
        //生成他入库单号
        String inNum = UUID.randomUUID().toString();
        inStock.setInNum(inNum);
        inStock.setStatus(2);
        inStock.setCreateTime(new Date());
        inStock.setModified(new Date());
        inStockMapper.insert(inStock);

        //添加到入库详情中
        //遍历集合
        for (Map map : productList){
            Integer productId = (Integer) map.get("productId");
            Integer productNumber = (Integer) map.get("productNumber");
            Product product = productMapper.selectByPrimaryKey(productId);
            if (product == null){
                throw new Exception("canshucuowu");
            }
            InStockInfo inStockInfo =new InStockInfo();
            inStockInfo.setInNum(inNum);
            //从集合中取出物资数量
            inStockInfo.setProductNumber(productNumber);
            //根据物资id查询物资单号插入
            inStockInfo.setPNum(product.getPNum());
            inStockInfo.setCreateTime(new Date());
            inStockInfo.setModifiedTime(new Date());
            inStockInfoMapper.insert(inStockInfo);

        }
    }


//        @Override
//        public InStockDetailVO detail(Long id, Integer pageNum, Integer pageSize)  {
//            InStockDetailVO inStockDetailVO = new InStockDetailVO();
//            //1.根据id查询出入库信息
//            InStock inStock = inStockMapper.selectByPrimaryKey(id);
//
//            BeanUtils.copyProperties(inStock,inStockDetailVO);
//            Supplier supplier = supplierMapper.selectByPrimaryKey(inStock.getSupplierId());
//
//            SupplierVO supplierVO = new SupplierVO();
//            BeanUtils.copyProperties(supplier,supplierVO);
//            inStockDetailVO.setSupplierVO(supplierVO);
//            String inNum = inStock.getInNum();//入库单号
//            //查询该单所有的物资
//            Example o = new Example(InStock.class);
//            PageHelper.startPage(pageNum,pageSize);
//            o.createCriteria().andEqualTo("inNum",inNum);
//        //        List<InStockInfo> inStockInfoList = inStockInfoMapper.selectByExample(o);
//        //        inStockDetailVO.setTotal(new PageInfo<>(inStockInfoList).getTotal());
//        //        if(!CollectionUtils.isEmpty(inStockInfoList)){
//        //            for (InStockInfo inStockInfo : inStockInfoList) {
//        //                String pNum = inStockInfo.getPNum();
//        //                //查出物资
//        //                Example o1 = new Example(Product.class);
//        //                o1.createCriteria().andEqualTo("pNum",pNum);
//        //                List<Product> products = productMapper.selectByExample(o1);
//        //                if(!CollectionUtils.isEmpty(products)){
//        //                    Product product = products.get(0);
//        //                    InStockItemVO inStockItemVO = new InStockItemVO();
//        //                    BeanUtils.copyProperties(product,inStockItemVO);
//        //                    inStockItemVO.setCount(inStockInfo.getProductNumber());
//        //                    inStockDetailVO.getItemVOS().add(inStockItemVO);
//        //                }else {
//        //                    throw new BusinessException(BusinessCodeEnum.PARAMETER_ERROR,"编号为:["+pNum+"]的物资找不到,或已被删除");
//        //                }
//        //            }
//        //        }else {
//        //            throw new BusinessException(BusinessCodeEnum.PARAMETER_ERROR,"入库编号为:["+inNum+"]的明细找不到,或已被删除");
//        //        }
//            return inStockDetailVO;
//        }
}
